import json
import sys
import pandas as pd
import numpy as np
import os
import traceback
import datetime
import regex as re

folder_prefix = "../"


def ExportLubanExcel():
    df = pd.read_excel(
        folder_prefix + "Excel/__auto_export.xlsx", header=None, sheet_name="Sheet1"
    )

    all_files = []
    rfiles = []
    single_configs = []

    for i in range(3, len(df)):
        file_name = df.iloc[i, 0]
        is_single_config = False
        if "@" in file_name:
            sdata = file_name.split("@")
            single_configs.append(file_name)
            file_name = sdata[1]
            sh_name = sdata[0]
            is_single_config = True

        if file_name in rfiles:
            continue

        mode_type = df.iloc[i, 1]

        rfiles.append(file_name)

        output_type = "map"
        if type(mode_type) == str:
            if len(mode_type) == 0:
                pass
            elif not is_single_config:
                output_type = mode_type
        elif np.isnan(mode_type):
            pass

        all_files.append([file_name, output_type])

    table_path = folder_prefix + "Excel/__tables__.xlsx"
    tdf = pd.read_excel(table_path, header=None, sheet_name="Sheet1")

    final_data = []
    for i in range(0, 3):
        rdata = []
        for j in range(0, len(tdf.columns)):
            rdata.append(tdf.iloc[i, j])

        final_data.append(rdata)

    for of in all_files:
        ex_fp = folder_prefix + "Excel/" + of[0]
        xl = pd.ExcelFile(ex_fp)
        st_names = xl.sheet_names
        xl.close()

        ex_file_name = os.path.splitext(of[0])[0]
        ex_file_name = ex_file_name[0].upper() + ex_file_name[1:]
        tb_name = "Tb" + ex_file_name

        c = 0
        for sname in st_names:
            if not "t_" in sname:
                continue

            sheet_name = sname.replace("t_", "")
            full_name = ex_file_name + "." + sheet_name + "Model"
            value_type = ex_file_name + "." + sheet_name + "Entity"
            input_name = sname + "@" + of[0]

            mode_type = of[1]
            sname = sname + "@" + of[0]
            if sname in single_configs:
                mode_type = "list"

            c += 1
            # print("{} {} {} {}".format(full_name, value_type, input_name, of[1]))

            final_data.append(
                [
                    "",
                    full_name,
                    value_type,
                    True,
                    input_name,
                    "",
                    mode_type,
                    "",
                    "",
                    "",
                    "",
                ]
            )

        if c == 0:
            print("[Error]{} has no t_ Sheet".format(of[0]))

    pfd = pd.DataFrame(final_data)
    pfd.to_excel(table_path, header=False, index=False)


if __name__ == "__main__":
    folder_prefix = ""
    ExportLubanExcel()
